<template>
  <div class="container mx-auto px-4 py-8">
    <div v-if="loading" class="flex justify-center py-8">
      <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
    </div>

    <div v-else-if="!order" class="text-center py-8">
      <p class="text-gray-500">订单不存在或已被取消</p>
      <button 
        @click="$router.push('/group-buy')"
        class="mt-4 px-4 py-2 bg-primary text-white rounded-md hover:bg-primary-dark transition"
      >
        返回团购列表
      </button>
    </div>

    <div v-else>
      <h1 class="text-2xl font-bold mb-6">团购订单确认</h1>
      
      <!-- 订单状态 -->
      <div class="bg-gray-50 p-4 rounded-lg mb-6">
        <div class="flex items-center">
          <span 
            :class="[
              'px-3 py-1 rounded-full text-sm mr-3',
              getStatusClass(order.status)
            ]"
          >
            {{ getStatusText(order.status) }}
          </span>
          <span class="text-gray-600">订单号: {{ order.orderNo }}</span>
        </div>
      </div>
      
      <!-- 商品信息 -->
      <div class="bg-white rounded-lg shadow-sm mb-6 overflow-hidden">
        <div class="p-4 border-b">
          <h2 class="font-semibold">商品信息</h2>
        </div>
        <div class="p-4">
          <div class="flex items-center">
            <img 
              :src="order.groupBuy.productImage || '/placeholder.png'" 
              :alt="order.groupBuy.productName"
              class="w-20 h-20 object-cover rounded mr-4"
            />
            <div class="flex-1">
              <h3 class="font-medium mb-1">{{ order.groupBuy.productName }}</h3>
              <div class="flex justify-between text-sm text-gray-600">
                <span>团购价: ¥{{ order.groupBuy.groupPrice }}</span>
                <span>数量: {{ order.quantity }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 订单信息 -->
      <div class="bg-white rounded-lg shadow-sm mb-6 overflow-hidden">
        <div class="p-4 border-b">
          <h2 class="font-semibold">订单信息</h2>
        </div>
        <div class="p-4">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <p class="text-gray-600 mb-2">订单创建时间: {{ formatDateTime(order.createTime) }}</p>
              <p v-if="order.payTime" class="text-gray-600 mb-2">支付时间: {{ formatDateTime(order.payTime) }}</p>
              <p class="text-gray-600">订单状态: {{ getStatusText(order.status) }}</p>
            </div>
            <div>
              <p class="text-gray-600 mb-2">团购活动: {{ order.groupBuy.productName }}</p>
              <p class="text-gray-600 mb-2">参团人数: {{ order.groupBuy.joinCount }}/{{ order.groupBuy.minCount }}</p>
              <p class="text-gray-600">
                活动状态: 
                <span :class="getGroupBuyStatusClass(order.groupBuy.status)">
                  {{ getGroupBuyStatusText(order.groupBuy.status) }}
                </span>
              </p>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 收货信息 -->
      <div class="bg-white rounded-lg shadow-sm mb-6 overflow-hidden">
        <div class="p-4 border-b">
          <h2 class="font-semibold">收货信息</h2>
        </div>
        <div class="p-4">
          <div v-if="order.address" class="mb-4">
            <p class="mb-2">
              <span class="font-medium">{{ order.address.name }}</span>
              <span class="ml-4">{{ order.address.phone }}</span>
            </p>
            <p class="text-gray-600">{{ order.address.province }} {{ order.address.city }} {{ order.address.district }} {{ order.address.detail }}</p>
          </div>
          
          <div v-else-if="order.status === 0" class="mb-4">
            <div v-if="addresses.length > 0">
              <div class="mb-4">
                <label class="block text-gray-700 mb-2">选择收货地址</label>
                <select 
                  v-model="selectedAddressId" 
                  class="w-full p-2 border border-gray-300 rounded"
                >
                  <option 
                    v-for="address in addresses" 
                    :key="address.id" 
                    :value="address.id"
                  >
                    {{ address.name }} - {{ address.phone }} - {{ address.province }} {{ address.city }} {{ address.detail }}
                  </option>
                </select>
              </div>
            </div>
            <div v-else class="text-gray-500 mb-4">
              您还没有添加收货地址，请先添加收货地址
            </div>
            
            <button 
              @click="$router.push('/profile?tab=address')"
              class="text-primary hover:underline"
            >
              管理收货地址
            </button>
          </div>
          
          <div v-else class="text-gray-500">
            暂无收货信息
          </div>
        </div>
      </div>
      
      <!-- 支付信息 -->
      <div class="bg-white rounded-lg shadow-sm mb-6 overflow-hidden">
        <div class="p-4 border-b">
          <h2 class="font-semibold">支付信息</h2>
        </div>
        <div class="p-4">
          <div class="flex justify-between items-center mb-4">
            <span class="text-gray-600">商品金额:</span>
            <span>¥{{ (order.groupBuy.groupPrice * order.quantity).toFixed(2) }}</span>
          </div>
          <div class="flex justify-between items-center mb-4">
            <span class="text-gray-600">运费:</span>
            <span>¥0.00</span>
          </div>
          <div class="flex justify-between items-center text-lg font-bold">
            <span>实付金额:</span>
            <span class="text-red-500">¥{{ order.amount.toFixed(2) }}</span>
          </div>
        </div>
      </div>
      
      <!-- 操作按钮 -->
      <div class="flex justify-end">
        <button 
          v-if="order.status === 0"
          @click="cancelOrder"
          class="px-4 py-2 border border-gray-300 rounded-md mr-4 hover:bg-gray-50 transition"
          :disabled="isProcessing"
          :class="{'opacity-50 cursor-not-allowed': isProcessing}"
        >
          取消订单
        </button>
        
        <button 
          v-if="order.status === 0"
          @click="payOrder"
          class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary-dark transition"
          :disabled="isProcessing || !selectedAddressId"
          :class="{'opacity-50 cursor-not-allowed': isProcessing || !selectedAddressId}"
        >
          <span v-if="isProcessing">处理中...</span>
          <span v-else>立即支付</span>
        </button>
        
        <button 
          v-if="order.status === 1 || order.status === 2"
          @click="$router.push('/orders')"
          class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary-dark transition"
        >
          查看我的订单
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

export default {
  name: 'GroupBuyOrderView',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const order = ref(null)
    const loading = ref(true)
    const isProcessing = ref(false)
    const addresses = ref([])
    const selectedAddressId = ref(null)
    
    const fetchOrderDetail = async () => {
      loading.value = true
      try {
        const id = route.params.id
        const response = await axios.get(`/api/group-buy/order/${id}`)
        if (response.data.code === 200) {
          order.value = response.data.data
          
          // 如果订单已有地址，不需要选择
          if (order.value.address) {
            selectedAddressId.value = order.value.address.id
          }
          
          // 如果订单未支付，获取用户地址列表
          if (order.value.status === 0) {
            fetchAddresses()
          }
        } else {
          console.error('获取订单详情失败:', response.data.message)
        }
      } catch (error) {
        console.error('获取订单详情出错:', error)
      } finally {
        loading.value = false
      }
    }
    
    const fetchAddresses = async () => {
      try {
        const response = await axios.get('/api/address/list')
        if (response.data.code === 200) {
          addresses.value = response.data.data
          
          // 如果有地址，默认选择第一个
          if (addresses.value.length > 0) {
            selectedAddressId.value = addresses.value[0].id
          }
        } else {
          console.error('获取地址列表失败:', response.data.message)
        }
      } catch (error) {
        console.error('获取地址列表出错:', error)
      }
    }
    
    const getStatusText = (status) => {
      switch (status) {
        case 0: return '待支付'
        case 1: return '已支付'
        case 2: return '已完成'
        case 3: return '已取消'
        case 4: return '已退款'
        default: return '未知状态'
      }
    }

    const getStatusClass = (status) => {
      switch (status) {
        case 0: return 'bg-yellow-100 text-yellow-800'
        case 1: return 'bg-blue-100 text-blue-800'
        case 2: return 'bg-green-100 text-green-800'
        case 3: return 'bg-gray-100 text-gray-800'
        case 4: return 'bg-red-100 text-red-800'
        default: return 'bg-gray-100 text-gray-800'
      }
    }
    
    const getGroupBuyStatusText = (status) => {
      switch (status) {
        case 0: return '未开始'
        case 1: return '进行中'
        case 2: return '已结束'
        case 3: return '已取消'
        default: return '未知状态'
      }
    }

    const getGroupBuyStatusClass = (status) => {
      switch (status) {
        case 0: return 'text-blue-600'
        case 1: return 'text-green-600'
        case 2: return 'text-gray-600'
        case 3: return 'text-red-600'
        default: return 'text-gray-600'
      }
    }
    
    const formatDateTime = (timeString) => {
      if (!timeString) return '暂无'
      
      const date = new Date(timeString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }
    
    const cancelOrder = async () => {
      if (isProcessing.value) return
      
      if (!confirm('确定要取消该订单吗？')) {
        return
      }
      
      isProcessing.value = true
      try {
        const response = await axios.post(`/api/group-buy/order/${order.value.id}/cancel`)
        if (response.data.code === 200) {
          alert('订单已取消')
          // 刷新订单信息
          fetchOrderDetail()
        } else {
          alert(response.data.message || '取消订单失败，请稍后重试')
        }
      } catch (error) {
        console.error('取消订单出错:', error)
        alert('取消订单失败，请稍后重试')
      } finally {
        isProcessing.value = false
      }
    }
    
    const payOrder = async () => {
      if (isProcessing.value) return
      
      if (!selectedAddressId.value) {
        alert('请选择收货地址')
        return
      }
      
      isProcessing.value = true
      try {
        const response = await axios.post(`/api/group-buy/order/${order.value.id}/pay`, {
          addressId: selectedAddressId.value
        })
        
        if (response.data.code === 200) {
          alert('支付成功')
          // 刷新订单信息
          fetchOrderDetail()
        } else {
          alert(response.data.message || '支付失败，请稍后重试')
        }
      } catch (error) {
        console.error('支付出错:', error)
        alert('支付失败，请稍后重试')
      } finally {
        isProcessing.value = false
      }
    }
    
    onMounted(fetchOrderDetail)
    
    return {
      order,
      loading,
      isProcessing,
      addresses,
      selectedAddressId,
      getStatusText,
      getStatusClass,
      getGroupBuyStatusText,
      getGroupBuyStatusClass,
      formatDateTime,
      cancelOrder,
      payOrder
    }
  }
}
</script> 